package com.ktwlsoft.archivemanage.domain.business.businessService.study;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.config.FileStorageProperties;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.AccountRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.study.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.study.*;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.study.FindGroupAndContentByClassId;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.DateUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

/**
 * 课程管理
 *
 * @author Name on 2019/12/24 15:36
 * @version 1.0
 */
@Component
public class StudyManageService {

    /**课程*/
    private final StudyClassRepositoryService studyClassRepositoryService;

    /**专题*/
    private final StudySubjectRepositoryService studySubjectRepositoryService;

    /**课程内容*/
    private final StudyClassContentRepositoryService studyClassContentRepositoryService;

    /**账号业务层接口实现类*/
    private final AccountRepositoryService accountRepositoryService;

    /**课程评论*/
    private final StudyCommentRepositoryService commentService;

    /**课程分组*/
    private final StudyClassGroupRepositoryService classGroupService;

    /**课程收藏*/
    private final StudyCollectionRepositoryService collectionService;

    /**课程历史*/
    private final StudyHistoryRepositoryService historyRepositoryService;

    private final FileStorageProperties fileStorageProperties;

    public StudyManageService(StudyClassRepositoryService studyClassRepositoryService, StudySubjectRepositoryService studySubjectRepositoryService, StudyClassContentRepositoryService studyClassContentRepositoryService, AccountRepositoryService accountRepositoryService, StudyCommentRepositoryService commentService, StudyClassGroupRepositoryService classGroupService, StudyCollectionRepositoryService collectionService, StudyHistoryRepositoryService historyRepositoryService, FileStorageProperties fileStorageProperties) {
        this.studyClassRepositoryService = studyClassRepositoryService;
        this.studySubjectRepositoryService = studySubjectRepositoryService;
        this.studyClassContentRepositoryService = studyClassContentRepositoryService;
        this.accountRepositoryService = accountRepositoryService;
        this.commentService = commentService;
        this.classGroupService = classGroupService;
        this.collectionService = collectionService;
        this.historyRepositoryService = historyRepositoryService;
        this.fileStorageProperties = fileStorageProperties;
    }


    /**
     * 首页 on 2019/12/24 15:53
     *
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> home(String type){
        JSONObject retJson = new JSONObject();
        //横幅栏
        List<StudyClass> classList = studyClassRepositoryService.selectByBannerShow(1,type);
        List<JSONObject> list = Lists.newArrayList();
        if(classList != null && classList.size() > 0){
            classList.forEach(value ->{
                JSONObject object = new JSONObject();
                object.put("id",value.getId());
                object.put("bannerImgUrl",value.getBannerImgUrl());
                list.add(object);
            });
        }
        retJson.put("banners",list);
        //热门课程
        List<StudyClass> classes = studyClassRepositoryService.selectByLimitNum(4,type);
        List<StudyClassContent> contentlist = studyClassContentRepositoryService.selectAll();
        List<JSONObject> objects = Lists.newArrayList();
        if(classes != null && classes.size() > 0){
            for(StudyClass value:classes){
                JSONObject object2 = new JSONObject();
                object2.put("id",value.getId());
                object2.put("mainImgUrl",value.getMainImgUrl());
                object2.put("creator",value.getPublisherName());
                object2.put("title",value.getTitle());
                int i = 0;
                if(contentlist != null && contentlist.size() > 0){
                    for(StudyClassContent contentValue:contentlist){
                        if(value.getId().equals(contentValue.getClassId())){
                            i++;
                        }
                    }
                }
                object2.put("num",i);
                objects.add(object2);
            }
        }
        retJson.put("hots",objects);
        //热门专题
        List<StudySubject> studySubjects = studySubjectRepositoryService.selectByLimitNum(3,type);
        List<JSONObject> objectList = Lists.newArrayList();
        studySubjects.forEach(value ->{
            JSONObject object2 = new JSONObject();
            object2.put("id",value.getId());
            object2.put("mainImgUrl",value.getMainImgUrl());
            object2.put("title",value.getTitle());
            object2.put("tag",value.getTag());
            objectList.add(object2);
        });
        retJson.put("subjects",objectList);
        return Result.ok(retJson);
    }

    /**
     * 搜索列表 on 2019/12/24 16:53
     *
     * @param keyWords keyWords
     * @param classifyId classifyId
     * @param sortField sortField
     * @param sortType sortType
     * @return Result<?>
     */
    public Result<?> search(int pn,int pageSize,String keyWords,Long classifyId,String sortField,String sortType,String type){
        JSONObject object = new JSONObject();
        object.put("keyWords",keyWords != null?keyWords:null);
        object.put("classifyId",classifyId != null?classifyId:null);
        object.put("sortField",sortField != null?sortField.replaceAll("[A-Z]", "_$0").toLowerCase():null);
        object.put("sortType",sortType != null?("ascend").equals(sortType)?"ASC":"DESC":null);
        object.put("type",type);
        PageInfo<StudyClass> pageInfo = studyClassRepositoryService.findPage(pn,pageSize,object);
        if(pageInfo.getList() != null && pageInfo.getList().size() > 0){
            List<StudyClassContent> contentlist = studyClassContentRepositoryService.selectAll();
            List list = Lists.newArrayList();
            for(StudyClass value:pageInfo.getList()){
                JSONObject object1 = new JSONObject();
                object1.put("id",value.getId());
                object1.put("mainImgUrl",value.getMainImgUrl());
                object1.put("title",value.getTitle());
                object1.put("num",getNum(contentlist,value));
                object1.put("publisherName",value.getPublisherName());
                list.add(object1);
            }
            pageInfo.setList(list);
        }
        return Result.ok(pageInfo);
    }

    /**
     * 热门课程 on 2019/12/24 17:34
     *
     * @return Result<?>
     */
    public Result<?> moreHots(int pn,int pageSize,String type){
        PageInfo<StudyClass> pageInfo = studyClassRepositoryService.moreHotsPage(pn,pageSize,null,type);
        if(pageInfo.getList() != null && pageInfo.getList().size() > 0){
            List<StudyClassContent> contentlist = studyClassContentRepositoryService.selectAll();
            List list = Lists.newArrayList();
            for(StudyClass studyClass:pageInfo.getList()){
                JSONObject object = new JSONObject();
                object.put("id",studyClass.getId());
                object.put("title",studyClass.getTitle());
                object.put("mainImgUrl",studyClass.getMainImgUrl());
                object.put("num",getNum(contentlist,studyClass));
                object.put("publisherName",studyClass.getPublisherName());
                list.add(object);
            }
            pageInfo.setList(list);
        }
        return Result.ok(pageInfo);
    }

    /**
     * 课程详情 on 2019/12/24 17:45
     *
     * @param id id
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> getDetails(Long id){
        StudyClass studyClass = studyClassRepositoryService.selectByPrimaryKey(id);
        if(studyClass == null){
            return Result.body("课程不存在，无法查看！", ResultType.BUSINESS_SUCCESS);
        }
        Account currentUser = UserPrincipal.getCurrentUser();
        if(currentUser == null || currentUser.getId() <= 0){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("获取不到当前用户");
        }
        JSONObject data = new JSONObject();
        data.put("accountId",currentUser.getId());
        data.put("classId",studyClass.getId());
        StudyCollection collection = collectionService.getStudyCollectionMapper().getByAccountIdAndClassId(data);
        Account account = accountRepositoryService.getById(studyClass.getCreaterId());
        JSONObject object = new JSONObject();
        object.put("id",studyClass.getId());
        object.put("title",studyClass.getTitle());
        object.put("tag",studyClass.getTag());
        object.put("classifyId",studyClass.getClassifyId());
        object.put("subjectId",studyClass.getSubjectId());
        object.put("subjectName",studyClass.getSubjectName());
        object.put("classifyName",studyClass.getClassifyName());
        object.put("mainImgUrl",studyClass.getMainImgUrl());
        object.put("bannerShow",studyClass.getBannerShow());
        object.put("bannerImgUrl",studyClass.getBannerImgUrl());
        object.put("playTimes",studyClass.getPlayTime());
        object.put("publishorId",studyClass.getPublishorId());
        object.put("publisherName",studyClass.getPublisherName());
        object.put("publishAt",studyClass.getPublishAt());
        object.put("managedState",studyClass.getManagedState());
        object.put("manageRemark",studyClass.getManageRemark());
        object.put("state",studyClass.getState());
        object.put("classType",studyClass.getClassType());
        object.put("creatorIntroduce",account != null?account.getIntroduce():"");
        object.put("creator",account != null?account.getRealName():"");
        object.put("creatorTelephone",account != null?account.getTeleNum():"");
        object.put("teacherImg",account != null?account.getProfile():"");
        object.put("isCollection",collection != null);
        //分组
        JSONObject object1 = new JSONObject();
        object1.put("classId",studyClass.getId());
        object1.put("type",studyClass.getClassType());
        List<FindGroupAndContentByClassId> list = classGroupService.getStudyClassGroupMapper().findGroupAndContentByClassId(object1);
        if(list != null){
            list.forEach(value ->{
                if(value.getClassContent() != null && value.getClassContent().size() > 0){
                    value.getClassContent().forEach(itemValue ->{
                        if(itemValue.get("imgContent") != null){
                            try {
                                itemValue.put("imgContent",new String(itemValue.getBytes("imgContent"),"UTF-8"));
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        }
        object.put("classGroup",list);
        return Result.ok(object);
    }

    /**
      * 修改播放次数 on 2019/12/31 17:12
      *
      * @param id id
      * @return Result<?>
      */
    public Result<?> updatePlayTime(Long id){
        try {
            studyClassRepositoryService.getStudyClassMapper().updatePlayTime(id);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null, ResultType.UPDATE_ERROR);
        }
        return Result.ok(id);
    }

    /**
     * 评论分页 on 2019/12/25 9:58
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> comments(int pn,int pageSize,Long id){
        JSONObject object1 = new JSONObject();
        object1.put("classId",id);
        object1.put("passed",1);
        return Result.ok(commentService.findPage(pn,pageSize,object1));
    }

    /**
     * 我的收藏 on 2019/12/25 11:05
     *
     * @param accountId accountId
     * @return Result<?>
     */
    public Result<?> mine(int pn,int pageSize,Long accountId){
        JSONObject object = new JSONObject();
        object.put("accountId",accountId);
        object.put("classManagedState","NORMAL");
        return Result.ok(collectionService.findPage(pn,pageSize,object));
    }

    /**
     * 新增收藏 on 2019/12/31 9:22
     *
     * @param classId classId
     * @return Result<?>
     */
    public Result<?> collectionSave(Long classId){
        Account account = UserPrincipal.getCurrentUser();
        if(account == null || account.getId() == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("获取不到用户");
        }
        StudyClass studyClass = studyClassRepositoryService.selectByPrimaryKey(classId);
        if(studyClass == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该课程不存在");
        }
        JSONObject object = new JSONObject();
        object.put("accountId",account.getId());
        object.put("classId",studyClass.getId());
        StudyCollection studyCollection = collectionService.getStudyCollectionMapper().getByAccountIdAndClassId(object);
        if(studyCollection != null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该课程已收藏");
        }
        StudyCollection collection = new StudyCollection();
        collection.setId(SnowFlake.getNextId());
        collection.setAccountId(account.getId());
        collection.setUserName(account.getUserName());
        collection.setUserRealName(account.getRealName());
        collection.setUserProfile(account.getProfile());
        collection.setClassId(classId);
        collection.setClassTitle(studyClass.getTitle());
        collection.setClassManagedState(studyClass.getManagedState());
        collection.setClassState(studyClass.getState());
        collection.setClassImgUrl(studyClass.getMainImgUrl());
        try {
            collectionService.getStudyCollectionMapper().insert(collection);
            studyClassRepositoryService.getStudyClassMapper().plusCollectTime(studyClass.getId());
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null, ResultType.SAVING_ERROR);
        }
        return Result.ok(collection.getId());
    }

    /**
     * 取消收藏 on 2019/12/31 9:35
     *
     * @param collectionId collectionId
     * @return Result<?>
     */
    public Result<?> cancel(Long collectionId){
        StudyCollection collection = collectionService.getStudyCollectionMapper().selectByPrimaryKey(collectionId);
        if(collection == null){
            return Result.body(null,ResultType.CHECK_ERROR).withMessage("该收藏不存在");
        }
        try {
            studyClassRepositoryService.getStudyClassMapper().reduceCollectTime(collection.getClassId());
            collectionService.getStudyCollectionMapper().deleteByPrimaryKey(collection.getId());
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null,ResultType.DELETE_ERROR);
        }
        return Result.ok(collection.getId());
    }

    /**
     * 学习记录 on 2019/12/25 11:42
     *
     * @param accountId accountId
     * @return Result<?>
     */
    public Result<?> historyMine(int pn,int pageSize,Long accountId){
        JSONObject object = new JSONObject();
        object.put("accountId",accountId);
        PageInfo<JSONObject> pageInfo = historyRepositoryService.findPage(pn,pageSize,object);
        if(pageInfo.getList() != null && pageInfo.getList().size() > 0){
            pageInfo.getList().forEach(value ->{
                value.put("studyAt",value.get("studyAt") != null? DateUtils.dateToStr(value.getDate("studyAt"),DateUtils.SIMPLESF_PATTERN):"");
            });
        }
        return Result.ok(pageInfo);
    }

    /**
     * 新增学习记录 on 2019/12/31 9:45
     *
     * @param classId classId
     * @return Result<?>
     */
    public Result<?> historySave(Long classId){
        Account account = UserPrincipal.getCurrentUser();
        if(account == null || account.getId() == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("获取不到用户");
        }
        StudyClass studyClass = studyClassRepositoryService.selectByPrimaryKey(classId);
        if(studyClass == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该课程不存在");
        }
        JSONObject object = new JSONObject();
        object.put("accountId",account.getId());
        object.put("classId",studyClass.getId());
        StudyHistory data = historyRepositoryService.getStudyHistoryMapper().getByAccountIdAndClassId(object);
        StudyHistory studyHistory = null;
        if(data != null){
            studyHistory = data;
        }else{
            studyHistory = new StudyHistory();
            studyHistory.setId(SnowFlake.getNextId());
        }
        studyHistory.setAccountId(account.getId());
        studyHistory.setUserName(account.getUserName());
        studyHistory.setUserRealName(account.getRealName());
        studyHistory.setUserProfile(account.getProfile());
        studyHistory.setClassId(studyClass.getId());
        studyHistory.setClassTitle(studyClass.getTitle());
        studyHistory.setClassManagedState(studyClass.getManagedState());
        studyHistory.setClassState(studyClass.getState());
        studyHistory.setClassType(studyClass.getClassType().name());
        studyHistory.setStudyAt(new Date());
        studyHistory.setClassImgUrl(studyClass.getMainImgUrl());
        try {
            if(data != null) {
                historyRepositoryService.getStudyHistoryMapper().updateByPrimaryKey(studyHistory);
            }else{
                historyRepositoryService.getStudyHistoryMapper().insert(studyHistory);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null, ResultType.SAVING_ERROR);
        }
        return Result.ok(studyHistory.getId());
    }

    /**
     * 管理端课程文件预览 on 2019/12/31 10:28
     *
     * @param type 服务端:MANAGE,用户端:USER
     * @param url url
     * @return Result<?>
     */
    public ResponseEntity<?> view(String type,String url,HttpServletRequest request){
        if(url == null || "".equals(url)){
            return ResponseEntity.ok(Result.body(null, ResultType.CHECK_ERROR).withMessage("url为空"));
        }
        UrlResource urlResource = null;
        String contentType = null;
        try {
            Path path = Paths.get(url).toAbsolutePath().normalize();
            urlResource = new UrlResource(path.toUri());
            if (!urlResource.exists()) {
                return ResponseEntity.ok(Result.body(null, ResultType.CHECK_ERROR).withMessage("获取不到该文件"));
            }
            contentType = request.getServletContext().getMimeType(urlResource.getFile().getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(null, ResultType.BUSINESS_SUCCESS));
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).body(urlResource);
    }

    private int getNum(List<StudyClassContent> contentlist,StudyClass value){
        int i = 0;
        if(contentlist != null && contentlist.size() > 0){
            for(StudyClassContent content:contentlist){
                if(content.getClassId().equals(value.getId())){
                    i++;
                }
            }
        }
        return i;
    }
}